package org.auth.service.service;

import java.util.ArrayList;
import java.util.List;
import java.util.stream.Collectors;

import org.auth.service.JwtUser;
import org.auth.service.dao.BaseUserDAO;
import org.auth.service.model.BaseUser;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Service;
@Service
public class UserDetailServiceImpl implements UserDetailsService{

	@Autowired
    private BaseUserDAO baseUserDAO;

    @Override
    public JwtUser loadUserByUsername(String userName) throws UsernameNotFoundException {
    	System.out.println(userName);
        //获取本地用户
        BaseUser user = baseUserDAO.selectByUserName(userName);
        JwtUser jwtUser =new JwtUser();
        jwtUser.setAuthorities(mapToGrantedAuthorities());
        
        if(user != null){
        	jwtUser.setId(user.getId());
        	jwtUser.setUsername(userName);
        	jwtUser.setPassword(user.getPassword());
        	jwtUser.setAccountNonLocked(true);
        	jwtUser.setAccountNonExpired(true);
        	jwtUser.setEnabled(true);
        	jwtUser.setCredentialsNonExpired(true);
            return jwtUser ;
        }else{
            throw  new UsernameNotFoundException("用户["+userName+"]不存在");
        }
    }
    
    public static List<GrantedAuthority> mapToGrantedAuthorities() {
    	List<String> authorities = new ArrayList<String>();
    	authorities.add("ROLE_USER");
        return authorities.stream()
                .map(SimpleGrantedAuthority::new)
                .collect(Collectors.toList());
    }

}
